#!/usr/bin/env python
# -*- coding: utf-8 -*-
# datetime: 6/12/2023 下午10:00
# Author: name
# File: variable_api.py
# ide: PyCharm
# description:
from datetime import datetime
from typing import List

from fastapi import APIRouter, HTTPException, Query

from backend.app.models.variable_model import GlobalVariableOut, GlobalVariableIn, GlobalVariable, GlobalVariablePage
from backend.app.utils.response_tepmlate import ResponseCode

variable_router = APIRouter(prefix="/variable", tags=["全局变量"])


@variable_router.post("/add")
async def create_global_variable(variable: GlobalVariableIn):
    """
        新增全局变量

    :param item:
    :return:
    """
    select_variable = await GlobalVariable.filter(name=variable.name).first()
    if select_variable:
        return ResponseCode(variable.name).response_409()
    await GlobalVariable.create(
        name=variable.name,
        value=variable.value,
        created_at=datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
        updated_at=datetime.now().strftime("%Y-%m-%d %H:%M:%S")

    )
    return ResponseCode(f"变量{variable.name}").response_add()


# 获取全局变量列表（分页查询）
@variable_router.get("/page", response_model=GlobalVariablePage)
async def get_global_variables(
        page: int = Query(1, ge=1),
        size: int = Query(10, ge=1, le=100),
        name: str = Query(None, min_length=0)
):
    skip = (page - 1) * size
    query = GlobalVariable.all()
    if name:
        query = query.filter(name__icontains=name)
    total = await query.count()
    variables = await query.offset(skip).limit(size).values()
    return GlobalVariablePage(total=total, page_size=size, current_page=page, search_key=name, results=variables)


@variable_router.get("/list", response_model=List[GlobalVariableOut])
async def read_global_variables():
    return await GlobalVariable.all()


@variable_router.get("/{global_var_id}", response_model=GlobalVariableOut)
async def read_global_variable(global_var_id: int):
    global_var = await GlobalVariable.filter(id=global_var_id).first()
    if not global_var:
        return ResponseCode(global_var_id).response_404()
    return global_var


@variable_router.put("/{global_var_id}")
async def update_global_variable(global_var_id: int, variable: GlobalVariableIn):
    select_variable = await GlobalVariable.filter(id=global_var_id).first()
    select_other_variable = await GlobalVariable.exclude(id=global_var_id).filter(name=variable.name).first()
    if not select_variable:
        return ResponseCode(variable.name).response_404()
    if select_other_variable:
        return ResponseCode(variable.name).response_exist()
    await GlobalVariable.filter(id=global_var_id).update(
        name=variable.name,
        value=variable.value,
        updated_at=datetime.now().strftime("%Y-%m-%d %H:%M:%S")
    )
    update_global_variable = await GlobalVariable.filter(id=global_var_id).first()
    if not update_global_variable:
        return ResponseCode(variable.name).response_404()
    return ResponseCode(f"变量{variable.name}").response_update_success()


@variable_router.delete("/{global_var_id}", response_model=dict)
async def delete_global_variable(global_var_id: int):
    deleted_count = await GlobalVariable.filter(id=global_var_id).delete()
    if not deleted_count:
        return ResponseCode(global_var_id).response_404()
    return ResponseCode(f"{global_var_id}的变量").response_delete()
